package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器写法
@Component
public class LoginChaeckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session的值判断是否为空，判断是否登录
        Long empId=(Long) request.getSession().getAttribute("employee");
        Long userId=(Long) request.getSession().getAttribute("user");

        //判断购物界面是否登录
        if (userId!=null){
            BaseContext.setCurrentId(userId);
            return true;
        }

        //判断管理界面是否登录
        if (empId!=null){
            //返回JSON数据给前端
            BaseContext.setCurrentId(empId);
            return true;
        }
        //给baseContext设置ID值

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
